package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.SysMenu;
import com.cy.pj.common.pojo.SysUserMenu;
import com.cy.pj.common.vo.Node;
import com.cy.pj.sys.dao.SysMenuDao;

import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private  SysUserRoleDao sysUserRoleDao;
    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;
    @Override
    public List<Map<String, Object>> findObjects() {
        List<Map<String,Object>> list=
                sysMenuDao.findObjects();
        if(list==null||list.size()==0)
            throw new ServiceException("没有对应的菜单信息");
        return list;
    }

    @Override
    public List<Node> findZtreeMenuNodes() {
        return sysMenuDao.findZtreeMenuNodes();
    }

    @Override
    public int saveObject(SysMenu entity) {
        if(entity==null)
            throw new IllegalArgumentException("保存对象不能为空");
        if(StringUtils.isEmpty(entity.getName()))
            throw new IllegalArgumentException("菜单名不能为空");
//2.保存数据
        int rows=sysMenuDao.insertObject(entity);
//3.返回数据
        return rows;
    }

    @Override
    public int updateObject(SysMenu entity) {
        //1.合法验证
        if(entity==null)
            throw new ServiceException("保存对象不能为空");
        if(StringUtils.isEmpty(entity.getName()))

        throw new ServiceException("菜单名不能为空");
//2.更新数据
        int rows = sysMenuDao.updateObject(entity);
        if(rows==0)
            throw new ServiceException("记录可能已经不存在");
//3.返回数据
        return rows;
    }
    @Override
    public List<SysUserMenu> findUserMenusByUserId(Integer id) {
//1.对用户 id 进行判断
//2.基于用户 id 查找用户对应的角色 id

        List<Integer> roleIds=
                sysUserRoleDao.findRoleIdsByUserId(id);
//3.基于角色 id 获取角色对应的菜单信息,并进行封装.

        List<Integer> menuIds=
                sysRoleMenuDao.findMenuIdsByRoleIds(roleIds);
//4.基于菜单 id 获取用户对应的菜单信息并返回
        return sysMenuDao.findMenusByIds(menuIds);
    }
}
